import { reqGetJudgeList } from '../../api/judge';
Page({
  data: {
    judgeList: [],
    hasComments: false, // 新增标志位，用于判断是否有评论
    loading: true // 新增加载状态
  },
  onLoad: function(options) {
    const cakeid = options.cakeid;
    if (!cakeid) {
      wx.showToast({ title: '参数错误', icon: 'none' });
      return;
    }
    this.fetchComments(cakeid);
    
    wx.setNavigationBarColor({
      backgroundColor: '#FFB5C5',
      frontColor: '#000000',
      animation: { duration: 400, timingFunc: 'easeIn' }
    });
    wx.setNavigationBarTitle({ title: '评论页面' });
  },
  
  fetchComments: function(cakeid) {
    this.setData({ loading: true });
    reqGetJudgeList(cakeid)
      .then(res => {
        console.log(res);
        if (res.code === 200) {
          const comments = res.data.selectByCakeId;
          let judgeList = [];
          let hasComments = false;
          console.log("获取到的评论集合");
          console.log(res.data);
          console.log(res.data.selectByCakeId.imgurl)
          if (Array.isArray(comments) && comments.length > 0) {
            judgeList = comments.map(comment => {
              const images = comment.imgurl 
                ? comment.imgurl.split(';').map(img => this.processImagePath(img))
                : [];
              
              return {
                userName: comment.username || '匿名用户',
                date: this.formatDate(comment.discusstime),
                content: comment.discusscontent,
                images: images,
                avatar: this.processImagePath(comment.userurl),
                desc: comment.cakename,
                isLiked: false
              };
            });
            hasComments = true;
          }
          
          this.setData({ 
            judgeList,
            hasComments,
            loading: false
          });
        }
      })
      .catch(err => {
        console.error('Failed to fetch comments', err);
        this.setData({ loading: false });
      });
  },
  
  // 图片路径处理方法
  processImagePath: function(path) {
    if (!path) return '/images/default-avatar.png';
    // 如果是完整 URL，直接返回（无需截取）
    if (path.startsWith('http')) return path;
    // 仅处理本地路径
    const match = path.match(/[\\\/]images[\\\/].+$/);
    return match ? match[0].replace(/\\/g, '/') : '/images/default-avatar.png';
  },
  
  formatDate: function(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`;
  },
  
  // 图片预览方法
  previewImage: function(e) {
    const { imgs, index } = e.currentTarget.dataset;
    wx.previewImage({
      current: imgs[index],
      urls: imgs
    });
  },
      /**
   * 用户点击右上角分享
   */
  onshow: function () {
    this.fetchComments();
},
});